package step.xmpp.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("base/")
public class BaseController {
	private Logger logger=Logger.getLogger(this.getClass());
	private final static String SERVER="192.168.254.129";
	private final static Map<String,ChatManager> CMS=new HashMap<String, ChatManager>();
	private final static Map<String,Object> COREMAP=new HashMap<String,Object>();
	private final static Map<String,List<String>> MSG_CACHE_MAP=new HashMap<String,List<String>>();
	@RequestMapping("sendMsg")
	@ResponseBody
	public Map<String,Object> sendMsg(HttpServletRequest request,HttpServletResponse response){
		final String sessionId=request.getSession().getId();
		String toSend=request.getParameter("toSend");
		String target=request.getParameter("target");
		Map<String,Object> map=new HashMap<String, Object>();
		final ChatManager chatManager=CMS.get(sessionId);
		Chat chat =chatManager.getThreadChat(target+"@"+SERVER+"|"+sessionId);
		if(chat==null){
			chat = chatManager.createChat(target+"@192.168.254.129",target+"@"+SERVER+"|"+sessionId,null);
//			Thread thread=new Thread(new Runnable() {
//				public void run() {
//					chatManager.addChatListener(new ChatManagerListener() {
//						@Override
//						public void chatCreated(Chat chat, boolean createdLocally) {
//							chat.addMessageListener(new ChatMessageListener() {
//								@Override
//								public void processMessage(Chat chat, Message message) {
//									System.out.println("chat================="+message.getBody());
//									List<String> list = MSG_CACHE_MAP.get(sessionId);
//									if(list==null){
//										list=new ArrayList<String>();
//									}
//									list.add(message.getBody());
//									MSG_CACHE_MAP.put(sessionId, list);
//								}
//							});
//							
//						}
//					});
//					while (true) {
//						try {
//							Thread.currentThread().sleep(50l);
//						} catch (Exception e) {
//							logger.info("");
//						}
//					}
//				}
//			});
//			thread.start();
		}
		try {
			chat.sendMessage(toSend);
		} catch (Exception e) {
			logger.info("",e);
		}
//		while(true){
//			try {
//				Thread.currentThread().sleep(50l);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			map.put("status", "SUCCESS");
			return map;
//		}
	}
	@RequestMapping("loginChat")
	@ResponseBody
	public Map<String,Object> loginChat(HttpServletRequest request){
		Map<String,Object> statusMap=new HashMap<String,Object>();
		final String userName = request.getParameter("userName");
		final String password = request.getParameter("password");
		final String sessionId=request.getSession().getId();
		Thread thread=new Thread(new Runnable() {
			@Override
			public void run() {
				XMPPTCPConnection connection = SendUtils.getConnection(userName, password);
				final ChatManager chatManager = ChatManager.getInstanceFor(connection);
				Thread thread=new Thread(new Runnable() {
					public void run() {
						chatManager.addChatListener(new ChatManagerListener() {
							@Override
							public void chatCreated(Chat chat, boolean createdLocally) {
								chat.addMessageListener(new ChatMessageListener() {
									@Override
									public void processMessage(Chat chat, Message message) {
										System.out.println("chat================="+message.getBody());
										List<String> list = MSG_CACHE_MAP.get(sessionId);
										if(list==null){
											list=new ArrayList<String>();
										}
										list.add(message.getBody());
										MSG_CACHE_MAP.put(sessionId, list);
									}
								});
								
							}
						});
						while (true) {
							try {
								Thread.currentThread().sleep(50l);
							} catch (Exception e) {
								logger.info("");
							}
						}
					}
				});
				thread.start();
				CMS.put(sessionId,chatManager);
			}
		});
		thread.start();
		statusMap.put("stutus","SUCCESS");
		return statusMap;
		
	}
	@RequestMapping("getMsg")
	@ResponseBody
	public Map<String,Object> getMsg(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		String sessionId = request.getSession().getId();
		map.put("status","SUCCESS");
		List<String> msgs = MSG_CACHE_MAP.get(sessionId);
		MSG_CACHE_MAP.remove(sessionId);
		map.put("msgs",msgs);
		return map;
		
	}
	/**
	 * 查看是否有与本人相关的信息  有的话直接返回 没有的话保持连接 (暂定 一直连接 以后优化为微信类似)
	 */
	@RequestMapping("synccheck")
	@ResponseBody
	public Map<String,Object> synccheck(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		String sessionid = request.getSession().getId();
		COREMAP.get(sessionid);
		long sumTime=0;
		try {
			while(true){
				Thread.currentThread().sleep(50l);
				List<String> list = MSG_CACHE_MAP.get(sessionid);
				sumTime+=50l;
				if(sumTime>=30000l){
					map.put("isHasMsg","false");
					break;
				}
				if(list!=null&&list.size()>0){
					map.put("isHasMsg","true");
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("status","SUCCESS");
		return map;
	}
}
